<?php
namespace App\Base\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/5/17 0017
 * Time: 17:43
 */
class BaseModel extends Model{
    private $prefixByFields = 'models:';

    public function __construct(array $attributes = [])
    {
        //自动添加字段
        $this->setFillable();
        parent::__construct($attributes);
    }

    /**
     * 自动获取数据库表字段
     */
    protected function setFillable()
    {
        $key = get_class($this);
        $cache = Cache::get($this->prefixByFields . $this->getConnectionName() . ':' . $key);
        if (empty($cache)) {
            $cache = $this->getConnection()->getSchemaBuilder()->getColumnListing($this->table);
            Cache::put($this->prefixByFields . $this->getConnectionName() . ':' . $key, $cache, config('cache.columns'));
        }
        $this->fillable = $cache;
    }

    /**
     * 过滤掉非数据库字段的数据
     * @param $data
     * @return array
     */
    public function filter($data)
    {
        $result = [];
        if (empty($data) || !is_array($data)) {
            return $result;
        }

        foreach ($this->fillable as $item) {
            if (isset($data[$item])) {
                $result[$item] = $data[$item];
            }
        }
        return $result;
    }

    /**
     * Set the value of the "created at" attribute.
     *
     * @param  mixed $value
     * @return $this
     */
    public function setCreatedAt($value)
    {
        if (static::CREATED_AT) {
            $this->{static::CREATED_AT} = $value;
        }
        return $this;
    }

    /**
     * Set the value of the "updated at" attribute.
     *
     * @param  mixed $value
     * @return $this
     */
    public function setUpdatedAt($value)
    {
        if (static::UPDATED_AT) {
            $this->{static::UPDATED_AT} = $value;
        }
        return $this;
    }

    /**
     * 获取完整的表名
     * @return string
     */
    public function getTableRaw()
    {
        return $this->getConnection()->getTablePrefix() . $this->table;
    }
}